package service

import (
	"context"
	"encoding/json"
	"sale-admin/internal/app/grpc/client"
	"sale-admin/internal/app/grpc/protoc/system_admin"
	"sale-admin/internal/app/web/schema"
	"sale-admin/internal/dal"
	"sale-admin/internal/dao"
	"sale-admin/internal/define"
	"sale-admin/internal/models"
	"strings"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/logx"
	"gorm.io/gorm"
)

type PaymentsService struct{}

// 为商户设置支付方式
func (p PaymentsService) SetMerchantPayment(ctx context.Context, db *gorm.DB, loginMerchantID, PaymentsID, MerchantID string) (
	count int64, err error) {
	if strings.TrimSpace(MerchantID) == "" {
		err = errorx.New("商户ID不能为空", 1001)
		return
	}

	var Data = make(map[string]interface{})
	Data["payments_id"] = strings.TrimSpace(PaymentsID)
	count = db.Model(&models.MaMerchantConfig{}).
		Where("id = ?", MerchantID).
		Updates(&Data).
		RowsAffected
	return
}

// 删除支付配置
func (p PaymentsService) PaymentRemove(ctx context.Context, MerchantID string, PaymentID string, DetailID int) (count int64, err error) {
	// 默认获取全部
	if strings.TrimSpace(MerchantID) == "" {
		err = errorx.New("商户ID不能为空", 1001)
		return
	}
	err = dao.Payment{}.Delete(ctx, dal.Q, MerchantID, PaymentID, DetailID)
	return
}

// 为商户配置具体支付方式
func (p PaymentsService) SetThirdPay(ctx context.Context, merchantID string, Params schema.ThirdConfigData) (count int64, err error) {
	if strings.TrimSpace(merchantID) == "" {
		err = errorx.New("商户ID不能为空", 1001)
		return
	}
	var configBytes []byte
	// 根据payment_id解析不同类型的支付方式参数
	switch Params.PaymentID {
	case define.PaymentType_Wechat:
		config, err1 := PaymentsService{}.GetWechatPayConfig(ctx, Params)
		if err1 != nil {
			err = err1
			return
		}
		configBytes, _ = json.Marshal(config)
	case define.PaymentType_XiaoTianCai:
		config, err1 := PaymentsService{}.GetWechatPayConfig(ctx, Params)
		if err1 != nil {
			err = err1
			return
		}
		configBytes, _ = json.Marshal(config)
	case define.PaymentType_POS:
		configBytes = []byte{}
	case define.PaymentType_Alipay:
		config := schema.PaymentAlipay{}
		if _, ok := Params.PayInfo["ali_pay_app_id"]; ok {
			if Params.PayInfo["ali_pay_app_id"] != nil {
				config.AliPayAppID = Params.PayInfo["ali_pay_app_id"].(string)
			}
		}
		if _, ok := Params.PayInfo["ali_pay_private_key"]; ok {
			if Params.PayInfo["ali_pay_private_key"] != nil {
				config.AliPayPrivateKey = Params.PayInfo["ali_pay_private_key"].(string)
			}
		}
		configBytes, _ = json.Marshal(config)
	case define.PaymentType_JuHe:
		config := schema.PaymentJh{}
		if _, ok := Params.PayInfo["jh_merchant_num"]; ok {
			if Params.PayInfo["jh_merchant_num"] != nil {
				config.JhMerchantNum = Params.PayInfo["jh_merchant_num"].(string)
			}
		}
		if _, ok := Params.PayInfo["jh_api_key"]; ok {
			if Params.PayInfo["jh_api_key"] != nil {
				config.JhApiKey = Params.PayInfo["jh_api_key"].(string)
			}
		}
		configBytes, _ = json.Marshal(config)
	case define.PaymentType_DaXing:
		config := schema.PaymentDx{}
		if _, ok := Params.PayInfo["dx_app_id"]; ok {
			if Params.PayInfo["dx_app_id"] != nil {
				config.DxAppID = Params.PayInfo["dx_app_id"].(string)
			}
		}
		if _, ok := Params.PayInfo["dx_app_key"]; ok {
			if Params.PayInfo["dx_app_key"] != nil {
				config.DxAppKey = Params.PayInfo["dx_app_key"].(string)
			}
		}
		if _, ok := Params.PayInfo["dx_seller_id"]; ok {
			if Params.PayInfo["dx_seller_id"] != nil {
				config.DxSellerID = Params.PayInfo["dx_seller_id"].(string)
			}
		}
		if _, ok := Params.PayInfo["dx_merchant_id"]; ok {
			if Params.PayInfo["dx_merchant_id"] != nil {
				config.DxMerchantID = Params.PayInfo["dx_merchant_id"].(string)
			}
		}
		if _, ok := Params.PayInfo["dx_shop_id"]; ok {
			if Params.PayInfo["dx_shop_id"] != nil {
				config.DxShopID = Params.PayInfo["dx_shop_id"].(string)
			}
		}
		configBytes, _ = json.Marshal(config)
	case define.PaymentType_Stripe:
		config := schema.PaymentStripe{}
		if _, ok := Params.PayInfo["stripe_pub_key"]; ok {
			if Params.PayInfo["stripe_pub_key"] != nil {
				config.StripePubKey = Params.PayInfo["stripe_pub_key"].(string)
			}
		}
		if _, ok := Params.PayInfo["stripe_priv_key"]; ok {
			if Params.PayInfo["stripe_priv_key"] != nil {
				config.StripePrivKey = Params.PayInfo["stripe_priv_key"].(string)
			}
		}
		configBytes, _ = json.Marshal(config)
	}
	if Params.ID == 0 {
		count, err = dao.Payment{}.Create(ctx, dal.Q, merchantID, Params.PaymentID, 0,
			strings.TrimSpace(Params.Name), string(configBytes))
	} else {
		count, err = dao.Payment{}.Update(ctx, dal.Q, merchantID, Params.PaymentID, int(Params.ID),
			strings.TrimSpace(Params.Name), string(configBytes))
	}
	if count <= 0 {
		err = errorx.New("操作失败", -1)
		return
	}
	if err != nil || count < 0 {
		err = errorx.New("配置支付方式失败!", -1)
		return
	}
	return
}

// 微信配置
func (p PaymentsService) GetWechatPayConfig(ctx context.Context, Params schema.ThirdConfigData,
) (config schema.PaymentWechat, err error) {
	var certFile string
	if _, ok := Params.PayInfo["cert_file"]; ok {
		if Params.PayInfo["cert_file"] != nil {
			certFile = Params.PayInfo["cert_file"].(string) // 这里前端不对，要调整！
		}
	}
	if certFile == "" {
		err = errorx.New("证书不能为空!", -1)
		return
	}
	if !strings.HasSuffix(certFile, ".p12") {
		err = errorx.New("证书格式非法", -1)
		return
	}

	// 验证文件是否存在
	SystemAdminClient, clientErr := client.GetSystemAdminClient()
	if clientErr != nil {
		logx.Error(ctx, "cert confirm file error", logx.Any("err", clientErr.Error()))
		return
	}

	var req system_admin.ConfirmFileReq
	req.FileUrl = certFile
	res, err1 := SystemAdminClient.ConfirmFile(ctx, &req)
	if err1 != nil && res.Code != 0 {
		logx.Error(ctx, "cert confirm file error", logx.Any("res", res), logx.Any("err", err1.Error()))
		return
	} else {
		// 获取真实的地址
		if res.FileUrl != "" {
			config.CertFile = res.FileUrl
		}
	}
	if _, ok := Params.PayInfo["we_chat_app_id"]; ok {
		if Params.PayInfo["we_chat_app_id"] != nil {
			config.WeChatAppID = Params.PayInfo["we_chat_app_id"].(string)
		}
	}
	if _, ok := Params.PayInfo["we_chat_mch_id"]; ok {
		if Params.PayInfo["we_chat_mch_id"] != nil {
			config.WeChatMchID = Params.PayInfo["we_chat_mch_id"].(string)
		}
	}
	if _, ok := Params.PayInfo["we_chat_app_key"]; ok {
		if Params.PayInfo["we_chat_app_key"] != nil {
			config.WeChatAppKey = Params.PayInfo["we_chat_app_key"].(string)
		}
	}
	return
}
